from django import http
from django.core.paginator import Paginator
from django.shortcuts import render
from django.utils import timezone
from django.views import View
import json

from apps.contents.utils import get_categories
from apps.goods.models import GoodsCategory, SKU, GoodsVisitCount
from apps.goods.utils import get_breadcrumb
from utils.response_code import RETCODE


class ListView(View):
    """商品列表页"""

    def get(self, request, category_id, page_num):
        """提供商品列表页"""
        # 判断category_id是否正确
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return render(request, '404.html')

            # 查询面包屑导航
        breadcrumb = get_breadcrumb(category)

        sort = request.GET.get('sort')
        # 按照价格排序
        if sort == 'price':
            sort_field = 'price'
        # 按照人气排序
        elif sort == 'hot':
            sort_field = '-sales'
        # 按照默认排序
        else:
            sort = 'default'
            sort_field = 'create_time'

        skus = SKU.objects.filter(category=category).order_by(sort_field)
        # 分页
        try:
            paginator = Paginator(skus, 3)
            page_skus = paginator.page(page_num)
            total_pages = paginator.num_pages
        except Exception as e:
            return render(request, '404.html')

        # 查询商品频道分类
        # categories = get_categories()


        # 渲染页面
        context = {
            'category': category,  # 第三级分类
            'breadcrumb': breadcrumb,  # 面包屑导航
            'sort': sort,  # 排序字段
            'page_skus': page_skus,  # 分页后数据
            'page_num': page_num,  # 当前页码
            'total_page': total_pages,  # 总页数
        }
        return render(request, 'list.html', context=context)


# 热销排行
class HotGoodsView(View):
    def get(self, request, category_id, page_num):
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.JsonResponse({'code': RETCODE.NODATAERR, 'errmsg': '没有此分类'})

        skus = SKU.objects.filter(category_id=category_id).order_by('-sales')[:2]
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url,
            })
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'hot_skus': hot_skus})


"""商品详情页"""


class DetailView(View):
    def get(self, request, sku_id):
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request, '404.html')

            # 查询商品频道分类
        categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category)
        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options

        # 渲染页面
        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
        }
        """提供商品详情页"""
        return render(request, 'detail.html', context)


class DetailVisitView(View):
    def post(self, request, category_id):
        # 获取数据
        data = json.loads(request.body.decode())
        category_id = data.get('category_id')
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            return http.JsonResponse({'code': RETCODE.NODATAERR, 'errmsg': '缺少必传参数'})

        today = timezone.localtime()
        # 判断当天的当前的分类数据是否存在
        try:
            gvc = GoodsVisitCount.objects.get(category=category, data=today)
        except GoodsVisitCount.DoesNotExist:
            GoodsVisitCount.objects.create(category=category, data=today, count=1)
        else:
            gvc.count += 1
            gvc.save()
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok'})

